<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */



use \GatewayWorker\Lib\Gateway;
use \GatewayWorker\Lib\Db;
use \Workerman\Lib\Timer;

require_once '/vending/vendor/workerman/gateway-worker/src/Lib/Connection.php';

// 引入base
require_once __DIR__ . '/BaseController.php';
require_once __DIR__ . '/common/Rute.php';

use app\BaseController;
use app\common\Rute;

define('PATH', trim(__DIR__ . '/'));  

/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class Events
{   

    
    /**
     * 进程启动后初始化数据库连接
     */
    public static function onWorkerStart($worker)
    {
        global $redis;
        global $db;
        $db = new \Workerman\MySQL\Connection('127.0.0.1', '3306', 'root', '111111', 'shop');
        ini_set('default_socket_timeout', -1);
        $redis = new \Redis();
        $redis->pconnect('127.0.0.1',6379,0); 
    }



    /**
     * 当客户端连接时触发    
     * 如果业务不需此回调可以删除onConnect
     * 
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id)
    {
        if($_SERVER['GATEWAY_PORT'] == 8686){
            $_SESSION['app_type'] = 'pc';
            $_SESSION['user_id'] = $client_id;
        }
        if($_SERVER['GATEWAY_PORT'] == 8282){
            $_SESSION['app_type'] = 'pda';
            $_SESSION['user_id'] = $client_id;
        } 
        // Gateway::sendToCurrentClient('connect success'."\r\n");
    }



    /**
     * 当客户端发来消息时触发
     * @param int $client_id 连接id
     * @param mixed $message 具体消息
     */
    public static function onMessage($client_id, $message)
    {   
        // 格式化
        $request = json_decode($message,true);
        if(empty($request)){

            return Gateway::sendToCurrentClient(json_encode(array('error','数据格式不正确'))."\r\n");
            //用户IP
            // var_dump($_SERVER['REMOTE_ADDR']);
        }

        $_SESSION['returnType'] = isset($request['data']['returnType'])?$request['data']['returnType']:'';
        

        $rute = new Rute();
        $rute->entrance($message);

        // $base = new BaseController();
        

        // $base->log(date('Y-m-d H:i:s').': 用户发来信息');
        // $base->log($request);
        // 路由处理消息
        // $base->entrance($message);

        // 消息处理完成
    }




   
    /**
     * 当用户断开连接时触发
     * @param int $client_id 连接id
     */
    public static function onClose($client_id)
    {
        // GateWay::sendToAll("$client_id logout\r\n");
    }
}
